<template>
  <div class="app-container">
    <div class="main">
      <div class="filter-container g-bgc-fill-el-input">
        <div class="filter-left">
          <el-select v-model="listQuery.menufacturerId" placeholder="品牌" clearable @change="comHandleFilterSelectChange"
            style="width: 108px" class="filter-item">
            <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
              :value="item.id" />
          </el-select>
          <el-select v-model="listQuery.checkRole" placeholder="角色" clearable @change="comHandleFilterSelectChange"
            style="width: 108px" class="filter-item">
            <el-option v-for="(item, index) in UserRolesOptions" :key="'br' + index" :label="item.userName"
              :value="item.id" />
          </el-select>
          <!-- <el-select v-model="listQuery.founder" placeholder="创建人" clearable @change="comHandleFilterSelectChange"
            style="width: 90px" class="filter-item">
            <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
              :value="item.id" />
          </el-select> -->
          <el-date-picker v-model="listQuery.date" type="daterange" @change="comHandleFilterDateChange"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" style="width: 208px" range-separator=""
            start-placeholder="开始时间" end-placeholder="结束时间">
          </el-date-picker>
          <el-select v-model="listQuery.status" placeholder="状态" clearable @change="comHandleFilterSelectChange"
            style="width: 108px" class="filter-item">
            <el-option
              v-for="(item, index) in [{ id: 0, label: '未激活' }, { id: 1, label: '已启用' }, { id: 2, label: '已禁用' }]"
              :key="'st' + index" :label="item.label" :value="item.id" />
          </el-select>
          <np-input-search v-model="listQuery.keyword" placeholder="搜索登录账号、手机号" style="width: 360px;"
            @all-search="comHandleFilterAllSearch" />
        </div>
        <div class="filter-right" v-if="isOperatePermission">
          <el-button type="warning" @click="handleAddAccountNUm">新增账号</el-button>
        </div>
      </div>


      <el-table class="g-el-table" :data="list" v-loading="listLoading">
        <el-table-column label="登录账号" prop="username" width="80PX">
          <div slot-scope="{row}">
            {{ row.username }}
          </div>
        </el-table-column>
        <el-table-column label="品牌" width="120px">
          <template slot-scope="{row}">
            <span>{{ row.menufacturerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.role | roleFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" width="110px">
          <template slot-scope="{row}">
            <span>{{ row.phoneNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="80px">
          <template slot-scope="{row}">
            <span>{{ row.remarks }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="95">
          <template slot-scope="{row}">
            <span>{{ row.createBy }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="95">
          <template slot-scope="{row}">
            <span>{{ row.status | statusFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="95">
          <template slot-scope="{row}">
            <span>{{ row.createDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="95">
          <template slot-scope="{row}">
            <span>{{ row.updateDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}" v-if="isOperatePermission">
            <el-button type="text" @click="handleEditAccountNUm(row)">编辑</el-button>
            <el-button type="text" @click="handleDisableAccountNUm(row)" :disabled="row.delete_loading"
              :loading="row.disable_loading">
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" @click="handleDeleteAccountNUm(row)" :loading="row.delete_loading">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <np-pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
        @pagination="getList" />

    </div>

    <ListEditAccountNUmDialog :visible.sync="dialogEditAddAccountNUmVisible" :info-row="editAddInfoRow"
      :brand-options="brandOptions" :user-roles-options="UserRolesOptions"
      @editAddSuccessChange="editAddSuccessChange" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMenufacturers } from "@/api/family-and-users-management/index"
import { fetchList, puserUpdatePuser, puserDelPuser } from '@/api/backend-account-management/account/list'
import ListEditAccountNUmDialog from "./components/ListEditAccountNUmDialog.vue"

export default {
  name: 'ComplexTable',
  components: { ListEditAccountNUmDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: '已启用',
        1: '已启用',
        2: '已禁用'
      }
      return statusMap[status] || statusMap['0']
    },
    roleFilter(status) {
      const statusMap = {
        1: '爵奇管理员',
        2: '爵奇成员',
        3: '品牌商管理员',
        4: '品牌商成员',
      }
      return statusMap[status] || status
    },
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,

        menufacturerId: undefined,// 品牌
        role: undefined, // 当前账号角色
        checkRole: undefined, // 筛选的角色
        founder: undefined,// 创建人 没有这个字段
        status: undefined, // "状态 1已激活，0未激活，2已禁用")
        keyword: undefined,

        date: undefined,
        startDate: undefined,
        endDate: undefined,
      },
      brandOptions: [],
      p2pAddressOptions: [],

      // 编辑/添加账号弹窗需要的参数
      editAddInfoRow: null,
      dialogEditAddAccountNUmVisible: false,
    }
  },
  computed: {
    ...mapGetters([
      'userCurRole',
      'userRolesOptions',
    ]),
    isOperatePermission() {
      /**
       * 角色判断
       * 1爵奇管理员，2爵奇操作员，3品牌商管理员，4品牌商操作员
       * 判断角色是否有操作权限
       */
      return [1, 2, 3].includes(this.userCurRole)
    },
    UserRolesOptions() {
      try {
        let arr = JSON.parse(JSON.stringify(this.userRolesOptions))
        let v = arr.filter(el => {
          if (el.id === 1) {
            return false
          }
          if (this.userCurRole === 1) {
            return true
          }
          if (this.userCurRole === 2) {
            return el.id > this.userCurRole
          }
          if (this.userCurRole === 3) {
            return el.id > this.userCurRole
          }
          if (this.userCurRole === 4) {
          }
        })
        return v
      } catch (error) { }
      return []
    },
  },
  created() {
    this.getList()
    getMenufacturers({ pageNum: 1, pageSize: 1000 }).then(res => {
      if (res.code === 200) {
        this.brandOptions = res.data.list || []
      }
    })
  },
  methods: {
    getList() {
      let pans = { ...this.listQuery }
      delete pans.date
      pans.role = this.userCurRole

      if (this.userCurRole === 4) {
        this.listLoading = false
        return
      }
      if (this.userCurRole === 1) {
        delete pans.role
      }
      if (pans.checkRole) {
        delete pans.role
        if (![1, 2, 3, 4].includes(this.userCurRole)) {
          return
        }
      }

      this.listLoading = true
      fetchList(pans).then(res => {
        if (res.code === 200) {
          this.list = (res.data.list || []).map(el => {
            el.disable_loading = false
            el.delete_loading = false
            return el
          })
          this.total = res.data.total
        }

        // Just to simulate the time of the request
        this.listLoading = false
      }).catch(err => {
        this.listLoading = false
      })
    },
    comHandleFilterAllSearch(e, type) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterSelectChange(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterDateChange(e) {
      this.listQuery.pageNum = 1
      this.listQuery.startDate = e ? e[0] : ''
      this.listQuery.endDate = e ? e[1] : ''
      this.getList()
    },
    editAddSuccessChange(e) {
      // e 判断是编辑 edit 还是添加 add
      if (e === 'add') {
        this.getList()
        return
      }
      if (e === 'edit') {
        this.getList()
      }
    },
    handleAddAccountNUm() {
      this.editAddInfoRow = null
      this.dialogEditAddAccountNUmVisible = true
    },
    handleEditAccountNUm(row) {
      this.editAddInfoRow = row
      this.dialogEditAddAccountNUmVisible = true
    },
    handleDisableAccountNUm(row) {
      if (row.disable_loading) {
        return
      }
      let params = {
        id: row.id,
        status: 2
      }
      if (row.status !== 1) {
        params.status = 1
      }

      row.disable_loading = true
      puserUpdatePuser(params).then(res => {
        let data = row.status === 1 ? 1 : 0,
          obj = {
            0: '启用',
            1: '禁用',
          };
        if (res.code === 200) {
          this.$message.success(`${obj[data]}成功!`)
          this.getList()
          return
        } else {
          this.$message.error(`${obj[data]}失败。`)
        }
        row.disable_loading = false
      }).catch(err => {
        this.$message.error('系统错误，服务失败。')
        row.disable_loading = false
      })
    },
    handleDeleteAccountNUm(row) {
      if (row.delete_loading) {
        return
      }
      this.$confirm('确认删除此账户？请谨慎操作！')
        .then(_ => {
          row.delete_loading = true
          let params = { id: row.id }
          puserDelPuser(params).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功!')
              this.listQuery.pageNum = 1
              this.getList()
              return
            } else {
              this.$message.error('删除失败。')
            }
            row.delete_loading = false
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
            row.delete_loading = false
          })
        })
        .catch(_ => { });
    },
  }
}
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;
  overflow: auto;
}

.main {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px 20px 28px;
}

.filter-container {
  padding-bottom: 14px;
}
</style>